package com.qiaofang.applet.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * 百度地图工具类
 * @author junz.liu
 */
public class BaiduMapUtil {
    /**
     * 百度地图ak TODO 可以改为从集团表中获取
     */
    private static String ak = "M7XgQ69fP3FdzVX90c8w9qdaOYy1OwDO";

    /**
     * 根据经纬度获取城市信息接口地址
     */
    private static String url = "http://api.map.baidu.com/geocoder?location={LOCATION}&output=json&key={AK}";

    /**
     * 根据经纬度获取城市名
     * @param lat 纬度
     * @param lng 经度
     * @return
     */
    public static String getCityByLocation(String lat, String lng){
        String city = "未定位";
        String url = BaiduMapUtil.url;
        if(StringUtils.isBlank(lat) || StringUtils.isBlank(lng)) {
            return city;
        }
        String location = lat + "," + lng;
        url = url.replace("{LOCATION}", location).replace("{AK}", ak);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        if(!"OK".equals(jsonObject.get("status"))) {
            return city;
        }
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject json = result.getJSONObject("addressComponent");
        if(StringUtils.isBlank(json.getString("city"))) {
            return city;
        }
        return json.getString("city");
    }

    public static void main(String[] args) {
        System.out.println(getCityByLocation("28.213951", "112.942854"));
    }
}
